//SPDX-FileCopyrightText: Copyright 2022-2024 深圳市同心圆网络有限公司
//SPDX-License-Identifier: GPL-3.0-only

package api_coll_dao

import (
	"context"

	"atomgit.com/openlinksaas-org/api-server/dao/db_ns"
	"atomgit.com/openlinksaas-org/proto-gen-go.git/api_collection_api"
	"go.mongodb.org/mongo-driver/bson"
	"go.mongodb.org/mongo-driver/mongo"
)

type OpenApiExtraInfoDbItem struct {
	ApiCollId   string `bson:"_id"`
	ProtoFileId string `bson:"protoFileId"`
	NetProtocol string `bson:"netProtocol"`
}

func (item *OpenApiExtraInfoDbItem) ToOpenApiExtraInfo() *api_collection_api.OpenApiExtraInfo {
	return &api_collection_api.OpenApiExtraInfo{
		ApiCollId:   item.ApiCollId,
		ProtoFileId: item.ProtoFileId,
		NetProtocol: item.NetProtocol,
	}
}

type _OpenApiExtraDao struct {
	mc *mongo.Collection
}

func newOpenApiExtraDao(db *mongo.Database) (*_OpenApiExtraDao, error) {
	mc := db.Collection(db_ns.DB_NS_API_COLLECTION + "openapi")
	return &_OpenApiExtraDao{mc: mc}, nil
}

func (db *_OpenApiExtraDao) Insert(ctx context.Context, dbItem *OpenApiExtraInfoDbItem) error {
	_, err := db.mc.InsertOne(ctx, dbItem)
	return err
}

func (db *_OpenApiExtraDao) Update(ctx context.Context, apiCollId, protoFileId, netProtocol string) error {
	_, err := db.mc.UpdateOne(ctx, bson.M{"_id": apiCollId}, bson.M{"$set": bson.M{"protoFileId": protoFileId, "netProtocol": netProtocol}})
	return err
}

func (db *_OpenApiExtraDao) Exist(ctx context.Context, apiCollId string) (bool, error) {
	count, err := db.mc.CountDocuments(ctx, bson.M{"_id": apiCollId})
	return count > 0, err
}

func (db *_OpenApiExtraDao) Get(ctx context.Context, apiCollId string) (*OpenApiExtraInfoDbItem, error) {
	retItem := &OpenApiExtraInfoDbItem{}
	err := db.mc.FindOne(ctx, bson.M{"_id": apiCollId}).Decode(retItem)
	return retItem, err
}

func (db *_OpenApiExtraDao) Remove(ctx context.Context, apiCollId string) error {
	_, err := db.mc.DeleteOne(ctx, bson.M{"_id": apiCollId})
	return err
}
